<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/thor-toolkit" prefix="tt" %>
<!DOCTYPE html>
<html>
<head>
	<tt:env/>
    <title>对标管理平台</title>
    <meta charset="utf-8">
    <%@include file="../common-include.jspf"%>
    <style>
        .left-div{
            background-color:#C8C9CB;
            text-align:center;
        }
        .left-div-title{
            font-size:20px;
        }
        .link1{
            color:#555;
            cursor:pointer;
            text-decoration: underline;
        }
        .link1:hover{
            color:#007ded;
        }
        .tui-grid-line .link1{
            color:#555;
        }
        .tui-grid .tui-grid-line-selected .tui-grid-cell .tui-grid-cell-content .link1{
            color:#555;
        }
        .tui-grid-line-selected .tui-grid-cell .tui-grid-cell-content .link1{
            color:#fff;
        }
        .select-input{
        	width:300px;
        }
        .tipsback{
       		background-color:yellow;
        }
    </style>
    <script>
    	var grid;
    	var queryForm;
        $(function(){
            tui.ctrl.button("analysisImprove").checked(true);
            grid = tui.ctrl.grid("analysisGrid");
            
          //query comments
            queryForm=tui.ctrl.form("queryAnalysisForm");
            
            function getLastDay(d){
                var current=new Date(d);
                var currentMonth=current.getMonth();
                var nextMonth=++currentMonth;
                var nextMonthDayOne =new Date(current.getFullYear(),nextMonth,1);
                var minusDate=1000*60*60*24;
                return new Date(nextMonthDayOne.getTime()-minusDate);
           }
            
          	tui.ctrl.formAgent("endTimeAgent").on("getvalue",function(data){
          		if(data.value){
          			var lastDay = getLastDay(data.value);
          			data.value=lastDay.getFullYear() + "-" +(lastDay.getMonth()+1)+"-"+lastDay.getDate();
          		};
          	});
          	
          	
            tui.ctrl.button("runBtn").on("click",function(data){
            	queryForm.submit();
            });
            
            queryForm.on("receive", function(data){
           		tui.ctrl.paginator("pageBtn").totalSize(data.length);
           		grid.data(data);
           	});
            
            // add Analysis
            var sectionSelectData1=tui.ctrl.input("sectionData");
    		var kpiSelectData=tui.ctrl.input("kpiData");
            tui.ctrl.button("newAnalysisBtn").on("click",function(){
            	var dlg = tui.ctrl.dialog();
            	var diaSection;
            	var diaKpi;
            	var diaCom;
            	dlg.on("open",function(){
            		diaSection=tui.ctrl.input("diaSectionSelect");
                    diaKpi=tui.ctrl.input("diaKpiSelect");
                    diaCom=tui.ctrl.input("diaComSelect");
            		diaSection.data(sectionSelectData1.data());
            		$("#commentTr").css("display","none");
            		
            		//diaKpi.data(kpiSelectData.data());
            		var form=tui.ctrl.form("getKpiForm");
            		var form2=tui.ctrl.form("getComForm");
            		
            		diaSection.on("select",function(data){
            			form.immediateValue({sectionId:data.item[0]});
            			form.submit();
            			diaKpi.value(null);
            			form.once("receive",function(data){
            				diaKpi.data(data);
            			});
            			
            			form2.immediateValue({sectionId:data.item[0]});
            			form2.submit();
            			diaCom.value(null);
            			form2.once("receive",function(data){
            				diaCom.data(data);
            			});
            		});
            		
            	});
                dlg.showResource("editAnalysisHtml","新建分析改进",
                    [
                       {name:"保存", func: function(){
                    	   var fm=tui.ctrl.form("addAnalysisForm");
                    	   var proc = function() {
                               dlg.close();
                               fm.off("success", proc);
                           };
                           fm.immediateValue({KPI:diaKpi.value(),companyId:diaCom.value(),analysis:tui.ctrl.textarea("analysisInput").value(),improve:tui.ctrl.textarea("improveInput").value()});
                           fm.submitForm("queryAnalysisForm");
                           fm.submit();
                           fm.on("success",proc);
                       }},
                       {name:"取消", func: function(){
                           dlg.close();
                       }},
                 	]); 
            });
            var groupNameData;
            grid.columns([
	                          { key: 'checked', format: tui.ctrl.Grid.checkbox(true),width:30 ,fixed: true},
	                          { name: '时间', key: 'ReportDate',format:function(data){
	                        	  if(data.rowIndex<0){return;}
	                            	 data.cell.firstChild.innerHTML ="" ;
	                            	 data.cell.firstChild.innerHTML =data.value.substr(0,7);
	                          } },
	                          { name: '机构', key: 'DeptName' },
	                          { name: '指标', key: 'FiledName' },
	                          { name: '单位', key: 'FieldUnit' },
	                          { name: '标杆值', key: 'BenchmarkValue' },
	                          { name: '实际值', key: 'KeyValue' },
	                          { name: '差异分析', key: 'Analysis',format: function(data){
	                        	 if(data.rowIndex<0){return;}
                            	 if(data.cell.firstChild.innerHTML ==""){
                            		 $(data.cell.childNodes[0]).parent().parent().addClass("tipsback");
                            	 } else{
                            		 $(data.cell.childNodes[0]).parent().parent().removeClass("tipsback");
                            	 };
	                          }},
	                          { name: '改进措施', key: 'Improved'},
	                          { name: '最后编辑', key: 'lastEditUser'}
	                    ]);
            var gridMenu=[
						  {key: 'view', value: '查看'},
                          {key: 'contract', value: '联系人信息'}
             
						  ];
            function IsInArray(arr,val){
  			    var testStr=','+arr.join(",")+",";
  			    return testStr.indexOf(","+val+",")!=-1;
  			}
            grid.on("rowcontextmenu",function(data){
          	  	var m=tui.ctrl.menu(gridMenu);
          	  	var item=grid.activeItem();
              	m.show({x: data.event.clientX, y: data.event.clientY}, "rT");
              	m.on("select",function(data){
              		var checked=data.item.key;
              		if(checked==="view"){
              			var v=1;
              			editAnalysis(item,v);
              		}
              		if(checked==="edit"){
              			//判断一级及二级组成员
              			if(IsInArray(groupNameData,userGroupName)){
              				editAnalysis(item);
              			}else if(item[9]==userGroupName){
              				editAnalysis(item);
              			}else{
              				tui.infobox("没有编辑权限");
              			}
              			
              			
              		}
					if(checked==="contract"){
						if(item[14]){
							getUserInfo(item[14]);
						}else{
							tui.infobox("此条目无联系人信息","无联系人");
						}
              		}
					if(checked==="delete"){
						if(IsInArray(groupNameData,userGroupName)){
							if(item[24]){
								var arr=[];
								arr.push(item[24]);
								deleteAnalysis(arr);
							}else{
								tui.infobox("此条目无分析改进内容","无法删除");
							}
              			}else if(item[9]==userGroupName){
              				if(item[24]){
    							var arr=[];
    							arr.push(item[24]);
    							deleteAnalysis(arr);
    						}else{
    							tui.infobox("此条目无分析改进内容","无法删除");
    						}
              			}else{
              				tui.infobox("没有删除权限");
              			}
              			
						
					}
              	});
              	return tui.cancelDefault(data.event);
             });
            
            grid.on("rowdblclick",function(data){
            	var item=grid.activeItem();
            	editAnalysis(item,1);
            });
	     
          //delete Analysis function 
            function deleteAnalysis(ids){
				var fm=tui.ctrl.form();    
				fm.id("delAnalysisForm");
				fm.action("${root}/api/deleteAnalysis.do");
				fm.immediateValue({id:ids});
				fm.submitForm("queryAnalysisForm");
				tui.askbox("确认删除?","确认删除",function(result){
					if(result){
						fm.submit();
					}
            	});
				
            }
            
            //delete multiple Analysis
            var delBtn=tui.ctrl.button("delAnalysisBtn");
            delBtn.on("click",function(data){
            	var dt = grid.data();
            	var arr=[];
            	for (var i = 0; i < dt.length(); i++) {
            		if (dt.at(i)[0] == true) {
            			arr.push(dt.cell(i,"ID"));
            			if(IsInArray(groupNameData,userGroupName)){
            				
            			}else if(userGroupName==dt.cell(i,"DeptName")){
            				
            			}else{
            				tui.infobox("没有"+dt.cell(i,"DeptName")+"的删除权限");
            				return false;
            			}
            		}
            	}
            	if(arr[0]===null && arr.length===1){
        	  		tui.infobox("此条目无分析改进内容","无法删除");
        	  	}else if(arr.length===0){
            		tui.infobox("请选择要删除的条目");
            	}else{
           			deleteAnalysis(arr);
            	}
            });
            
          //modify comment
            function editAnalysis(item,v){
            	var dlg = tui.ctrl.dialog();
            	var textarea1;
            	var textarea2;
            	dlg.on("open",function(){
            		var sec=tui.ctrl.input("diaSectionSelect");
            		sec.data([{"key":item[22],"value":item[8]}]);
            		sec.value(item[22]);
            		sec.readonly(true);
            		
            		var kpi=tui.ctrl.input("diaKpiSelect");
            		kpi.data([{key:item[4],value:item[6]}]);
            		kpi.value(item[4]);
            		kpi.readonly(true);
            		
            		var com=tui.ctrl.input("diaComSelect");
            		com.data([{key:item[2],value:item[9]}]);
            		com.value(item[2]);
            		com.readonly(true);
            		
            		var diaDate=tui.ctrl.input("diaReportDate");
            		diaDate.value(item[3]);
            		diaDate.readonly(true);
            		
            		var diacomment=tui.ctrl.textarea("diaComment");
            		diacomment.value(item[23]);
            		diacomment.readonly(true);
            		
            		textarea1=tui.ctrl.textarea("analysisInput");
            		textarea1.value(item[12]);
            		textarea2=tui.ctrl.textarea("improveInput");
            		textarea2.value(item[13]);
            		
            		if(v==1){
            			textarea1.readonly(true);
            			textarea2.readonly(true);
            		}
            	});
            	var allBtn=[
                            {name:"取消", func: function(){
                                dlg.close();
                            }},
                      	];
            	var saveBtn={name:"保存", func: function(){
             	   var fm=tui.ctrl.form();
            	   fm.id("modifyAnalysisForm");
            	   if (item[12]!==null&&item[13]!==null){
                	   fm.action("${root}/api/modifyAnalysis.do");
                	   fm.immediateValue({id:item[24],analysis:textarea1.value(),improve:textarea2.value()});
            	   }else{
                	   fm.action("${root}/api/addAnalysis.do");
                	   fm.immediateValue({date:item[3],companyId:item[2],KPI:item[4], analysis:textarea1.value(),improve:textarea2.value()});
            	   }
            	   fm.submit();
            	   fm.submitForm("queryAnalysisForm");
            	   var proc = function() {
                       dlg.close();
                       fm.off("success", proc);
                   };
                   fm.once("success",proc);
                   
               }};
            	var text;
            	if(v!=1){
            		allBtn.push(saveBtn);
            		text="编辑分析改进";
            	}else{
            		text="查看分析改进";
            	}
                dlg.showResource("editAnalysisHtml",text,allBtn); 
            };
            tui.ctrl.paginator("pageBtn").on("change",function(){
            	queryForm.submit();
            });
            
            queryForm.once("success",function(){
            	ifExist();
            });
            function ifExist(){
            	for(var i=0;i<pointsData.length;i++){
            		a=(pointsData[i]=="manageAnalys");
                	if(pointsData[i]=="manageAnalys"){
                   		gridMenu.push( {key: 'edit', value: '编辑'},
                                {key: 'delete', value: '删除'});
                    }
                }
            }
            
            tui.ctrl.form("getPermissionGroupForm").on("receive",function(data){
            	var dat=data;
            	groupNameData=[];
            	for(var i=0;i<data.length;i++){
            		groupNameData.push(data[i].value);
            		if(data[i].children){
            			for(var a=0;a<data[i].children.length;a++)
            			groupNameData.push(data[i].children[a].value);
            		}
            	}
            });
            
        });
    </script>
    
    <!-- dialog Content -->
    <script id="editAnalysisHtml" type="text/html">
		<div style="padding:0 10px;width:400px;margin:0 auto;text-align:center">
			<table align="center">
				<tr>
					<td class="leftTd">板块：</td>
					<td><span id="diaSectionSelect" class="tui-input select-input"  data-type="select" data-validator= "{'*any':'请选择所属机构'}"></span></td>
				</tr>
				<tr>
					<td class="leftTd">指标：</td>
					<td><span id="diaKpiSelect" class="tui-input select-input" data-type="select"></span></td>
				</tr>
				<tr>
					<td class="leftTd">时间：</td>
					<td><span id="diaReportDate" class="tui-input select-input" data-type="calendar" data-month-only="true" data-date-format="yyyy-MM"></span></td>
				</tr>
				<tr>
					<td class="leftTd">机构：</td>
					<td><span id="diaComSelect" class="tui-input select-input" data-type="select"></span>
				</tr>
				<tr id="commentTr">
					<td style="vertical-align: top; padding-top: 10px;" class="leftTd">意见：</td>
					<td><span id="diaComment" class="tui-textarea select-input"></span></td>
				</tr>
				<tr>
					<td style="vertical-align: top; padding-top: 10px;">差异分析：</td>
					<td><span id="analysisInput" class="tui-textarea select-input"></span></td>
				</tr>
				<tr>
					<td style="vertical-align: top; padding-top: 10px;">改进措施：</td>
					<td><span id="improveInput" class="tui-textarea select-input"></span></td>
				</tr>
			</table>
		</div>
    </script>
</head>
<body>
   <%@include file="../main-common-include.jspf"%>
   <%@include file="../common-header.jspf"%>
    <!---左侧筛选栏--->
    <div class="contDiv">
   		<p class="left-div-title">差异分析及改进措施筛选</p>
        <div>
            板块：<span id="sectionSelect" class="tui-input"  data-placeholder="选择板块" data-type="select" data-clearable="true"></span>
        </div>
        <div>
            指标：<span id="kpiSelect" class="tui-input"  data-placeholder="选择指标" data-type="multi-select"></span>
        </div>
        <div>
            时间：<span id="startSelect" style="width:105px;display:inline-block" class="tui-input" data-clearable="true" data-type="calendar" data-month-only="true" data-date-format="yyyy-MM" data-placeholder="选择日期">
            </span>-<span id="endSelect"
             style="width:105px;display:inline-block" class="tui-input" data-type="calendar" data-clearable="true" data-month-only="true" data-date-format="yyyy-MM" data-placeholder="选择日期"></span>
        </div>
        <div>
            机构：<span id="comSelect" class="tui-input"  data-placeholder="选择机构" data-type="multi-select"></span>
        </div>
        <a id="runBtn" class="tui-button run-btn">运行</a>
   	</div>
    <div class="left-div left-body">
    	
    </div>

    <!---右侧--->
    <div class="right-body">
        <div id="manageAnalys" style="float:right;display:none">
            <a id="newAnalysisBtn" class="tui-button tui-primary tui-hidden">新建分析改进</a>
            <a id="delAnalysisBtn" class="tui-button tui-default">删除分析改进</a>
        </div>
        <div style="clear:both;margin-bottom:10px"></div>
        <div id="analysisGrid" class="tui-grid"
          data-resizable="true"
          data-rowselectable="true"
          style="width:100%;height:510px;"></div>
        <div style="clear:both;margin-bottom:10px"></div>
        <div id="pageBtn" class="tui-paginator" style="float:right" data-page-size="10" data-max-buttons="3"></div>
    </div>
</body>
<span id="queryAnalysisForm" class="tui-form" data-action="${root}/api/queryAnalysis.do" data-waiting="正在加载,请稍后..." >
	<span data-field="sectionId" data-target="sectionSelect"></span>
	<span id="sectionsAgent" data-field="sections"></span>
	<span data-field="KPIs" data-target="kpiSelect"></span>
	<span data-field="companyId" data-target="comSelect"></span>
	<span data-field="startTime" data-target="startSelect" ></span>
	<span id="endTimeAgent" data-field="endTime" data-target="endSelect"></span>
	<span data-field="page" data-target="pageBtn" ></span>
</span>
<span id="addAnalysisForm" class="tui-form" data-action="${root}/api/addAnalysis.do"></span>
<span id="getPermissionGroupForm" class="tui-form" data-method="get" data-auto-submit="true" data-action="${root}/action/sysListPermissionGroup"></span>
</html>
